package com.hongye.why.base.listenin;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;

/**
 * 消息队列发送线程处理
 */
public class MessagePosterHandler extends Handler {
    /**
     *
     */
    private final MessagePosterQueue posterQueue;
    /**
     *
     */
    private final int maxMillisInsideHandlePoster;
    /**
     *
     */
    private final Listenin listenin;
    /**
     * 是否活跃
     */
    private boolean isActive;

    MessagePosterHandler(int maxMillisInsideHandlePoster, Looper looper, Listenin listenin) {
        super(looper);
        this.listenin = listenin;
        posterQueue = new MessagePosterQueue();
        this.maxMillisInsideHandlePoster = maxMillisInsideHandlePoster;

    }

    /**
     *
     * @param poster MessagePoster
     */
    public void enqueue(MessagePoster poster) {
        synchronized (this) {
            this.posterQueue.enqueue(poster);
            if (!isActive) {
                this.isActive = true;
                if (!sendMessage(obtainMessage())) {
                    throw new RuntimeException("Could not send handler message");
                }
            }
        }
    }

    @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();

            long timeInMethod;
            do {
                MessagePoster poster = this.posterQueue.poll();
                if (poster == null) {
                    synchronized (this) {
                        poster = this.posterQueue.poll();
                        if (poster == null) {
                            isActive = false;
                            return;
                        }
                    }
                }
                this.listenin.invokePoster(poster);
                timeInMethod = SystemClock.uptimeMillis() - started;
            } while (timeInMethod < maxMillisInsideHandlePoster);

            if(!this.sendMessage(this.obtainMessage())) {
                throw new RuntimeException("Could not send handler message");
            }
            rescheduled = true;
        } finally {
            isActive = rescheduled;
        }

    }
}
